<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\fetch\kuaishou;

use app\enum\CommonEnum;
use app\enum\ConfigEnum;
use app\enum\KuaiShouEnum;
use app\model\ClientAccountModel;
use app\model\mongo\MongoKsUserVideoModel;
use app\service\client\AccountService;
use app\service\fetch\MediaInterface;
use app\service\kuaishou\MaterialService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

final class MongoVideoStatusDelService extends KuaiShouService implements MediaInterface
{
    /**
     * @var string 数据拉取key
     */
    protected const FETCH_KEY = ConfigEnum::CACHE_CONFIG[KuaiShouEnum::LIST_CONFIG_LOCK_KEY]['mongo_video_status_del'];

    /**
     * 获取视频素材.
     *
     * @param string $advertiserId 账户id
     */
    public static function getVideo(string $advertiserId = ''): bool
    {
        try {
            // 获取账户信息
            $obj = AccountService::getAccountModel(0, $advertiserId);
            if (! $obj instanceof ClientAccountModel || ! $obj->getKey()) {
                return self::setError('账户数据不存在');
            }
            // 获取user-id
            $userId = AccountService::getKsUserId($advertiserId);
            if (! $userId) {
                return self::setError('获取user_id失败');
            }
            $page = 0;
            while (true) {
                $result = self::getList($advertiserId, ++$page);
                if ($result === false) {
                    return false;
                }
                if (count($result['data']['details']) == 0) {
                    break;
                }
                foreach ($result['data']['details'] as $item) {
                    $model = self::getInfo($userId, $item['photo_id']);
                    if ($model) {
                        $item['update_time'] = time();
                        $item['upload_time'] = $item['upload_time'] ? strtotime($item['upload_time']) : '';
                        $item['photo_tag'] = $item['photo_tag'] ?: [];
                        $item['photo_tag_identify_items'] = $item['photo_tag_identify_items'] ?: [];
                        $item['user_id'] = $userId;
                        $item['client_id'] = intval($obj->getAttr('client_id'));
                        $item['company_id'] = intval($obj->getAttr('company_id'));
                        $model->setAttrs($item);
                        if (! $model->save()) {
                            throw new \Exception('保存数据出错');
                        }
                        if (! self::updateSchemaUrlVideoNum($userId, $item['photo_name'])) {
                            throw new \Exception(self::getError(0));
                        }
                    }
                }
            }
            return true;
        } catch (\Exception $e) {
            return self::setError($e->getMessage());
        }
    }

    /**
     * 获取视频素材列表.
     *
     * @param string $advertiserId 账户id
     * @param int $page 页数
     * @return bool|mixed|string
     */
    private static function getList(string $advertiserId = '', int $page = 1)
    {
        $token = AccountService::getToken(CommonEnum::KS_MEDIA, $advertiserId);
        if (! $token) {
            return self::setError('token获取失败');
        }
        $headers = [
            'Access-Token' => $token,
            'Content-Type' => 'application/json',
        ];
        $params = [
            'advertiser_id' => $advertiserId,
            'new_status' => KuaiShouEnum::VIDEO_STATUS_DELETE,
            'page' => $page,
            'page_size' => KuaiShouEnum::MAX_PAGE_SIZE,
        ];
        return MaterialService::getVideoList($headers, $params);
    }

    /**
     * 获取视频信息.
     * @param string $userId user-id
     * @param string $photoId 视频id
     * @return null|array|mixed|Model|MongoKsUserVideoModel
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getInfo(string $userId = '', string $photoId = '')
    {
        $where = [
            ['user_id', '=', $userId],
            ['photo_id', '=', $photoId],
            ['new_status', '>', KuaiShouEnum::VIDEO_STATUS_DELETE],
        ];
        return (new MongoKsUserVideoModel())->where($where)->field(true)->find();
    }
}
